<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>WebSocket 聊天室</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 40px auto;
            max-width: 600px;
            text-align: center;
        }
        #chat {
            border: 1px solid #ccc;
            height: 300px;
            overflow-y: auto;
            padding: 10px;
            margin-bottom: 10px;
        }
        #message {
            width: 70%;
            padding: 8px;
        }
        #send {
            padding: 8px 16px;
            cursor: pointer;
        }
    </style>
</head>
<body>
<h2>💬 简易 WebSocket 聊天室</h2>
<div id="chat"></div>

<input type="text" id="message" placeholder="输入消息...">
<button id="send">发送</button>

<script>
    // 建立 WebSocket 连接
    const socket = new WebSocket("ws://localhost:8080/api/ws/chat");

    const chatBox = document.getElementById("chat");
    const messageInput = document.getElementById("message");
    const sendBtn = document.getElementById("send");

    socket.onopen = () => {
        chatBox.innerHTML += "<p><em>✅ 已连接到服务器</em></p>";
    };

    socket.onmessage = (event) => {
        chatBox.innerHTML += "<p>" + event.data + "</p>";
        chatBox.scrollTop = chatBox.scrollHeight; // 滚动到底部
    };

    socket.onclose = () => {
        chatBox.innerHTML += "<p><em>❌ 连接已关闭</em></p>";
    };

    sendBtn.onclick = () => {
        const msg = messageInput.value.trim();
        if (msg) {
            socket.send(msg);
            messageInput.value = "";
        }
    };

    messageInput.addEventListener("keypress", (e) => {
        if (e.key === "Enter") sendBtn.click();
    });
</script>
</body>
</html>
